package com.robaone.util;

import java.io.FileReader;
import java.util.Hashtable;
import com.robaone.util.Strmanip;
import java.util.Vector;
/**
 * <pre>   Copyright Mar 21, 2012 Ansel Robateau
         http://www.robaone.com

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.</pre>
 * @author Ansel
 *
 */
public class INIFileReader {
  protected FileReader m_file;
  protected Hashtable<String,String> m_inientries;
  public INIFileReader(String filename) throws Exception {
    this.m_file = new FileReader(filename);
    this.m_inientries = new Hashtable<String,String>();
    this.ParseFile();
    this.m_file.close();
  }
  public String getValue(String key) throws Exception {
    return this.m_inientries.get(key).toString();
  }
  protected void ParseFile() throws Exception {
    String buffer = "";
    for(int i = this.m_file.read();i != -1;i = this.m_file.read()){
      char c = (char)i;
      if(c == '\n'){
        // Process the string then clear the buffer
        this.ProccessString(buffer);
        buffer = "";
      }else{
        // Add the character to the string
        buffer += c;
      }
    }
    if(buffer.length() > 0){
      // Process the string
      this.ProccessString(buffer);
    }
  }
  protected void ProccessString(String line){
    Vector<String> tokens = Strmanip.split('=',line);
    INIValue value = null;
    if(tokens.size() > 0){
      value = new INIValue(tokens.get(0).toString().trim(),null);
      if(tokens.size() > 1){
        String buffer = "";
        for(int i = 1;i < tokens.size();i++){
          if(i > 1) buffer += "=";
          buffer += tokens.get(i).toString();
        }
        value.setValue(buffer);
      }
    }
    if(value != null && value.getValue() != null){
      this.m_inientries.put(value.getKey(),value.getValue());
    }
  }
  protected class INIValue {
    private String m_key;
    private String m_value;
    public INIValue(String key,String value){
      this.m_key = key;
      this.m_value = value;
    }
    public String getKey(){
      return this.m_key;
    }
    public String getValue(){
      return this.m_value;
    }
    public void setKey(String key){
      this.m_key = key;
    }
    public void setValue(String value){
      this.m_value = value;
    }
  }
}